const { log, e, appendHtml } = require('../helper')
const { ipcRenderer } = require('electron')

const ajax = (request) => {
    let r = new XMLHttpRequest()
    r.open(request.method, request.url, true)
    if (request.contentType !== undefined) {
        r.setRequestHeader('Content-Type', request.contentType)
    }
    r.onreadystatechange = () => {
        if (r.readyState === 4) {
            request.callback(r.response)
        }
    }
    if (request.method === 'GET') {
        r.send()
    } else {
        r.send(request.data)
    }
}

const saveSearchData = (r) => {
    // 拿到响应中保存搜索结果歌曲信息的数组
    let arr = r.result.songs
    // 提取结果中的 音乐标题 网易云id 歌手 专辑等 信息,返回一个数组
    let searchResult = arr.map((e) => {
        let item = {}
        item.name = e.name
        item.duration = e.duration
        item.cloudId = e.id
        item.singer = e.artists[0].name
        item.singerId = e.artists[0].id
        item.album = e.album.name
        item.albumId = e.album.id
        return item
    })
    return searchResult
}

// 用 ajax 发送请求，调用网易云 api
// const ajaxSearchMusic = (keyword) => {
//     log('ajaxOnReady')
//     let url = `http://music.163.com/api/search/get/web?csrf_token=hlpretag=&hlposttag=&s=${keyword}&type=1&offset=0&total=true&limit=10`
//     // keywords.forEach((e) => {
//     //     if(typeof e === 'string') {
//     //         url += ' ' + e
//     //     }
//     // })
//     let request = {
//         method: 'GET',
//         url: url,
//         data: {},
//         callback: (response) => {
//             let r = JSON.parse(response)
//             log('response', r)
//             let searchResult = saveSearchData(r)
//             renderSearchResult(searchResult)
//         }
//     }
//     ajax(request)
// }

const renderSearchResult = (searchResult) => {
    log('searchResult', searchResult)
    let ul = e('#id-ul-search')
    let musicList = searchResult.reduce((html, music) => {
        html = html + `
            <li class="row music-track list-group-item d-flex justify-content-start align-items-center ">
                <div class="ml-4">${music.name}</div>
                <div class="ml-4">${music.singer}</div>
                <div class="ml-4">${music.album}</div>
            </li>
            `
        return html
    }, '')
    ul.innerHTML = musicList
}

// 给 搜索按钮音乐 绑定事件
e('#id-button-search').addEventListener('click', (event) => {
    // 拿到输入框的 搜索关键词
    let inputValue = e('#id-input-search').value
    // 将关键字用空格分词 转换成数组传递给主进程处理
    // let inputArr = inputValue.split(' ')
    // ajaxSearchMusic(inputValue)

    // ipcRenderer.send('req-music', inputValue)
    inputValue = encodeURIComponent(inputValue)
    log('发起请求')
    let url = `http://music.163.com/api/search/get/web?csrf_token=hlpretag=&hlposttag=&s=${inputValue}&type=1&offset=0&total=true&limit=10`
    fetch(url)
    .then((res) => {
        log('请求成功:', res.json())
        const searchResult = saveSearchData(res.json())
        renderSearchResult(searchResult)    
    })
})



